package bar.dark.lee.setting.password;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.select.SelectUpdateActivity;
import bar.dark.lee.setting.data.DataOutActivity;

public class PasswordSettingActivity extends SuperActivity {
	/** 패스워드 입력 에디트 텍스트 */
	private EditText passwordEdit1;
	private EditText passwordEdit2;
	private EditText passwordEdit3;
	private EditText passwordEdit4;
	
	private TextView textTitle;
	
	/** 패스워드 입력 버튼 */
	private Button passwordButton;
	
	/** 사용자 패스워드 값 */ 
	private String password = "";
	
	/** 사용자 입력 패스워드 값*/
	private String inputPassword = "";
	
	private String [][] passwords = new String[4][4];
	
	public static final int FIRST_RUN = 0;
	private static final int SECOND_RUN = 1;
	public static final int CONFIRM_RUN = 2;
	private static final int TEMP_RUN = 3;
	
	private int runState = FIRST_RUN;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.setting_password_setting);
		
		Intent intent = getIntent();
		runState = intent.getIntExtra("passwordRunState", FIRST_RUN);
		
		switch (runState) {
			case FIRST_RUN:
				setTitle("비밀번호 입력");
				break;
			case SECOND_RUN:
				setTitle("비밀번호 확인");
				break;		
			case CONFIRM_RUN:
				setTitle("비밀번호 확인");
				break;	
			default:
				break;
		}
		
		setFindView();
		setOnClickListener();
		//setData();
		
		Handler handler = new Handler(new Handler.Callback()
		{
			@Override
			public boolean handleMessage(Message msg)
			{
				InputMethodManager mgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
				mgr.showSoftInput(passwordEdit1, InputMethodManager.SHOW_IMPLICIT);
				return false;
			}
		});
		handler.sendMessageDelayed(new Message(), 300);
	}

	private void setFindView()
	{
		passwordEdit1 = (EditText) findViewById(R.id.settingPassword1);
		passwordEdit2 = (EditText) findViewById(R.id.settingPassword2);
		passwordEdit3 = (EditText) findViewById(R.id.settingPassword3);
		passwordEdit4 = (EditText) findViewById(R.id.settingPassword4);
		//passwordButton = (Button) findViewById(R.id.introPasswordButton);
		
		textTitle = (TextView) findViewById(R.id.settingPassword_text);
	}
	
	private void setOnClickListener()
	{
		passwordEdit1.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
			}
			
			@Override
			public void afterTextChanged(Editable s)
			{
				if (!s.toString().equals(""))
				{
					passwordEdit2.requestFocus();
					passwords[runState][0] = s.toString();
				}
			}
		});
		
		passwordEdit2.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
			}
			
			@Override
			public void afterTextChanged(Editable s)
			{
				if (!s.toString().equals(""))
				{
					passwordEdit3.requestFocus();
					passwords[runState][1] = s.toString();
				}
			}
		});
		
		passwordEdit3.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
			}
			
			@Override
			public void afterTextChanged(Editable s)
			{
				if (!s.toString().equals(""))
				{
					passwordEdit4.requestFocus();
					passwords[runState][2] = s.toString();
				}
			}
		});
		
		passwordEdit4.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
			}
			
			@Override
			public void afterTextChanged(Editable s)
			{
				if (!s.toString().equals(""))
				{
					passwords[runState][3] = s.toString();
					
					switch (runState) 
					{
						case FIRST_RUN:
							runState = TEMP_RUN;
							
							passwordEdit1.setText("");
							passwordEdit2.setText("");
							passwordEdit3.setText("");
							passwordEdit4.setText("");
	
							passwordEdit1.requestFocus();
							
							textTitle.setText("비밀번호를 다시 한번 입력해주세요.");
							
							runState = SECOND_RUN;
							break;
						case SECOND_RUN:
							String inputPassword = "";
							String inputPassword2 = "";
							for (int j = 0; j < 4; j++)
							{
								inputPassword += passwords[FIRST_RUN][j]; 
								inputPassword2 += passwords[SECOND_RUN][j];
							}
							
							if (!inputPassword.equals(inputPassword2)) {
								runState = TEMP_RUN;
								
								passwordEdit1.setText("");
								passwordEdit2.setText("");
								passwordEdit3.setText("");
								passwordEdit4.setText("");
	
								passwordEdit1.requestFocus();
								
								textTitle.setText("비밀번호가 틀렸습니다.\n비밀번호를 다시 한번 입력해주세요.");
								
								runState = SECOND_RUN;
							} 
							else 
							{
								new ShowDialog().execute(0);
							}
							
							break;		
						case CONFIRM_RUN:
							SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
							String password = pref.getString(BDConstents.PASSWORD, "");
							
							inputPassword = "";
							for (int i = 0; i < 4; i++)
							{
								inputPassword += passwords[CONFIRM_RUN][i]; 
							}
							
							if (password.equals(inputPassword)) {
								runState = TEMP_RUN;
								
								passwordEdit1.setText("");
								passwordEdit2.setText("");
								passwordEdit3.setText("");
								passwordEdit4.setText("");
	
								passwordEdit1.requestFocus();
								
								textTitle.setText("변경할 비밀번호를 입력해주세요.");
								
								runState = FIRST_RUN;
							} else {
								runState = TEMP_RUN;
								
								passwordEdit1.setText("");
								passwordEdit2.setText("");
								passwordEdit3.setText("");
								passwordEdit4.setText("");
	
								passwordEdit1.requestFocus();
								
								textTitle.setText("비밀번호가 틀렸습니다.\n비밀번호를 입력해주세요.");
								
								runState = CONFIRM_RUN;
							}
							
							break;	
						default:
							break;
					}
				}
			}
		});
		
		passwordEdit2.setOnKeyListener(new OnKeyListener()
		{
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (keyCode == KeyEvent.KEYCODE_DEL)
				{
					EditText et = (EditText) v;
					if (et.getText().toString().equals(""))
					{
						passwordEdit1.setText("");
						passwordEdit1.requestFocus();
					}
				}
				
				return false;
			}
		});
		
		passwordEdit3.setOnKeyListener(new OnKeyListener()
		{
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (keyCode == KeyEvent.KEYCODE_DEL)
				{
					EditText et = (EditText) v;
					if (et.getText().toString().equals(""))
					{
						et.setText("");
						passwordEdit2.requestFocus();
					}
				}
				
				return false;
			}
		});
		
		passwordEdit4.setOnKeyListener(new OnKeyListener()
		{
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (keyCode == KeyEvent.KEYCODE_DEL)
				{
					EditText et = (EditText) v;
					if (et.getText().toString().equals(""))
					{
						et.setText("");
						passwordEdit3.requestFocus();
					}
				}
				
				return false;
			}
		});
		
//		passwordButton.setOnClickListener(new OnClickListener()
//		{
//			@Override
//			public void onClick(View v)
//			{
//				Intent intent = new Intent(IntroPasswordActivity.this, DataOutActivity.class);
//				startActivity(intent);
//			}
//		});
	}

	private void setData()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int passwordSetting = pref.getInt(BDConstents.PASSWORD_SETTING, 0);
		password = pref.getString(BDConstents.PASSWORD, "");
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(PasswordSettingActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = pref.edit();
				editor.putInt(BDConstents.PASSWORD_SETTING, 1);
				inputPassword = "";
				
				for (int j = 0; j < 4; j++)
				{
					inputPassword += passwords[FIRST_RUN][j]; 
				}
			
				editor.putString(BDConstents.PASSWORD, inputPassword);
				editor.commit();
				
				return 0;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				BDUtil.showToast(PasswordSettingActivity.this, "비밀번호 설정이 완료되었습니다.");
				setResult(Activity.RESULT_OK);
				finish();
			}
		}
	}
	
	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(PasswordSettingActivity.this, DataOutActivity.class);
		startActivity(intent);
	}
}
